<!-- eslint-disable vue/multi-word-component-names -->
<template>
	<div class="chat-message-container" id="chat-message" :class="type === 'web' ? 'web' : ''">
		<template v-for="(item, index) in chatMessage">
			<div :key="index" v-if="type === 'web' ? item.label === 'agent' && item.fromUser.name === agent.userName : item.label === 'customer' && item.fromUser.name === client.userName">
				<Time v-if="item.showTime" :time="item.date" />
				<div class="agent-box">
					<div class="agent-message">
						<p class="agent-name">{{ type === 'web' ? `${$t('agent')}` + item.fromUser.name : item.fromUser.name }}</p>
						<div class="message-box">
							<template v-if="item.type === 'text' || item.type === 'link'">
								<MessageStatus v-if="item.status === 'in-progress' || item.status === 'failed'" :status="item.status" :isMobile="isMobile" />
								<div class="text" @click="e => openMessage(item, e)">
									<Message :message="item" :type="item.type" />
								</div>
							</template>
							<template v-else-if="getMsgType(item.type)">
								<p class="zco-business-message">{{ $t('cmd') }}</p>
								<Business :message="item" :businessType="item.type" />
							</template>
						</div>
					</div>
				</div>
			</div>
			<div :key="index" v-else-if="item.label !== 'system'">
				<Time v-if="item.showTime" :time="item.date" />
				<div class="client-box">
					<div class="client-message">
						<p class="client-name">{{ `${item.label === 'customer' ? '' : `${$t('agent')}`} ` + item.fromUser.name }}</p>
						<div class="message-box">
							<template v-if="item.type === 'text' || item.type === 'link'">
								<div class="text" @click="e => openMessage(item, e)">
									<Message :message="item" :type="item.type" />
								</div>
								<MessageStatus v-if="item.status === 'down'" :status="item.status" :isMobile="isMobile" />
							</template>
							<template v-else-if="getMsgType(item.type)">
								<Business :message="item" :businessType="item.type" />
								<p class="zco-business-message">{{ $t('cmd') }}</p>
							</template>
						</div>
					</div>
				</div>
			</div>
			<div :key="index" v-else-if="item.label === 'system'">
				<Time :time="item.date" />
				<SystemMessage :message="item.data" />
			</div>
		</template>
	</div>
</template>

<script>
import SystemMessage from '../SystemMessage/index.vue';
import Time from '../Time/index.vue';
import Message from './Message.vue';
import MessageStatus from './MessageStatus.vue';
import zcoIMEvent from '@/store/event';
import ZcoIM from '../../index';
import { isSafari, isAndroidWechat, copyToClipboard, isMobile } from '../../utils/util';
import { saveAs } from 'file-saver';
import Business from '../../Business/index.vue';

export default {
	components: { SystemMessage, Time, Message, MessageStatus, Business },
	props: {
		isMobile: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			chatMessage: [],
			agent: ZcoIM.agent,
			client: ZcoIM.client,
			previewImagesURL: null, //
			previewPdfURL: null,
			type: ZcoIM.type,
			isSafari: isSafari(),
			isAndroidWechat: isAndroidWechat(),
			previewRichText: null,
			previewVideoURL: '', // 视频预览地址
			previewLinkURL: '', // 链接预览地址
		};
	},
	watch: {},
	computed: {
		getMsgType() {
			return function (type) {
				return (
					(type === 'peer-cmd' ||
						type === 'peer-cancel' ||
						type === 'peer-response' ||
						type === 'screen-share' ||
						type === 'stop-screen-share' ||
						type === 'screen-record' ||
						type === 'stop-screen-record' ||
						type === 'ocr' ||
						type === 'start-tts-speaking' ||
						type === 'cancel-tts-speaking' ||
						type === 'ai-checkout' ||
						type === 'invite' ||
						type === 'invite-customer' ||
						type === 'request-upgrade' ||
						type === 'cancel-upgrade' ||
						type === 'accept-upgrade' ||
						type === 'reject-upgrade' ||
						type === 'start-recording' ||
						type === 'stop-recording' ||
                        type === 'system-start-recording' ||
						type === 'system-stop-recording') &&
					ZcoIM.showBusinessMessage
				);
			};
		}
	},
	methods: {
		openMessage(data, event) {
			event.preventDefault();
			if (data.type !== 'link' && typeof data.data === 'string' && !data.data.startsWith('http')) return;
			if (ZcoIM.type === 'web') {
				if (data.fromUser.name === this.agent.userName && data.clientId === this.agent.clientId) {
					this.ownMessage(data);
				} else {
					this.othersMessage(data);
				}
			} else {
				if (data.fromUser.name === this.client.userName && data.clientId === this.client.clientId) {
					this.ownMessage(data);
				} else {
					this.othersMessage(data);
				}
			}
		},

		//当前用户的消息预览
		ownMessage(data) {
			if (typeof data.data === 'string' && data.data.startsWith('http')) {
				this.previewLinkURL = data.data.replace(/^http(s)?:\/\//, 'https://');
				this.$emit('preview', { type: 'link', url: this.previewLinkURL });
				return;
			}
			switch (data.data.type) {
				//图片
				case 'pic':
					this.previewImagesURL = data.data.url?.replace(/^http(s)?:\/\//, 'https://');
					this.$emit('preview', { type: 'img', url: this.previewImagesURL });
					break;
				case 'doc':
					if (data.data.suffix === 'pdf') {
						this.previewPdfURL = data.data.url?.replace(/^http(s)?:\/\//, 'https://');
						if (isMobile()) {
							// 访客端, 使用pdf.js预览
							this.previewPdfURL = './static/pdf/web/viewer.html?file=' + encodeURIComponent(this.previewPdfURL);
						}
						this.$emit('preview', { type: 'pdf', url: this.previewPdfURL });
					}
					break;
				//视频
				case 'video':
					this.previewVideoURL = data.data.url.replace(/^http(s)?:\/\//, 'https://');
					this.$emit('preview', { type: 'video', url: this.previewVideoURL });
					break;
				default:
					break;
			}
		},

		//其他用户的消息预览和下载
		othersMessage(data) {
			if (typeof data.data === 'string' && data.data.startsWith('http')) {
				this.previewLinkURL = data.data.replace(/^http(s)?:\/\//, 'https://');
				this.$emit('preview', { type: 'link', url: this.previewLinkURL });
				return;
			}
			switch (data.data.type) {
				//图片
				case 'pic':
					this.previewImagesURL = data.data.url?.replace(/^http(s)?:\/\//, 'https://');
					this.$emit('preview', { type: 'img', url: this.previewImagesURL });
					break;
				case 'doc':
					if (data.data.suffix === 'pdf') {
						this.previewPdfURL = data.data.url.replace(/^http(s)?:\/\//, 'https://');
						if (isMobile()) {
							// 访客端, 使用pdf.js预览
							this.previewPdfURL = './static/pdf/web/viewer.html?file=' + encodeURIComponent(this.previewPdfURL);
						}
						this.$emit('preview', { type: 'pdf', url: this.previewPdfURL });
					} else if (['mov', 'mp4'].includes(data.data.suffix)) {
						this.previewVideoURL = data.data.url.replace(/^http(s)?:\/\//, 'https://');
						this.$emit('preview', { type: 'video', url: this.previewVideoURL });
					} else {
						// 移动端：拷贝+提示
						if (this.isMobile) {
							let url = data.data.url.replace(/^http(s)?:\/\//, 'https://');
							copyToClipboard(url);
							this.$zcoMessage({
								type: 'info',
								message: this.$t('copyed'), // `已复制文件链接，浏览器打开后下载预览！`,
								duration: 3
							});
						} else {
							this.downFile(data);
						}
					}
					break;
				//视频
				case 'video':
					this.previewVideoURL = data.data.url.replace(/^http(s)?:\/\//, 'https://');
					this.$emit('preview', { type: 'video', url: this.previewVideoURL });
					break;
				default:
					break;
			}
		},

		//下载文件
		downFile(data) {
			const xhr = new XMLHttpRequest(); // 创建xhr对象
			const fileUrl = data.data.url;
			const filename = data.data.name;
			const fileSize = data.data.size;
			let url = fileUrl.replace(/^http(s)?:\/\//, 'https://');

			xhr.open('GET', url);
			// 设置服务端的响应类型
			xhr.responseType = 'blob';
			// 监听下载
			// xhr.addEventListener(
			// 	'progress',
			// 	event => {
			// 		// 计算出百分比
			// 		const percent = ((event.loaded / event.total) * 100).toFixed(2);
			// 		console.log(`zco-im:下载进度：${percent}`, '+', new Date());
			// 		if (percent === '100.00') {
			// 			ZcoIM.sendMessage(data, 'down');
			// 		}
			// 	},
			// 	false
			// );
			xhr.onreadystatechange = res => {
				if (xhr.readyState === XMLHttpRequest.DONE) {
					const status = xhr.status;
					if (status === 0 || (status >= 200 && status < 400)) {
						// The request has been completed successfully
						// 是否已下载到内存
						// 文件名称（自定义）
						// const fileName = filename;
						// 创建一个a标签用于下载（固定写法）
						// const donwLoadLink = document.createElement('a');
						// donwLoadLink.download = filename;
						// donwLoadLink.rel = 'noopener'; // tabnabbing
						// if (xhr.response) {
						// 	donwLoadLink.target = '_blank'; // _blank | imgIframe-box
						// 	donwLoadLink.href = URL.createObjectURL(xhr.response);
						// }
						// // 触发下载事件，将从后端保存到内容的文件下载到到磁盘
						// donwLoadLink.click();
						// // 释放内存中的资源
						// URL.revokeObjectURL(donwLoadLink.href);
						// if ((this.isSafari && this.isMobile) || this.isAndroidWechat) {
						// 	// iOS Safari 禁止“显示”，显示会打开新tab页，引起本地camera采集中断
						// 	// Android 微信浏览器，提示默认浏览器打开
						// 	const blob = new Blob([xhr.response], { type: '' });
						// 	saveAs(blob, filename);
						// } else {
						// 	saveAs(xhr.response, filename);
						// }
						saveAs(xhr.response, filename);

						if (res && res.target && res.target.response && res.target.response.size && res.target.response.size === fileSize) {
							// iOS Safari 和 Android 微信浏览器，不显示下载完成
							if (!(this.isSafari && this.isMobile) && !this.isAndroidWechat) {
								ZcoIM.sendMessage(data, 'down');
							}
							console.log('zco-im-fileDownEx:下载成功+', new Date());
						}

						// if (this.isAndroidWechat) {
						// 	copyToClipboard(url);
						// }
					} else if (status == 404) {
						console.log('zco-im-fileDownEx:文件不存在+', new Date());
					} else if (status == 500) {
						console.log('zco-im-fileDownEx:系统异常+', new Date());
					}
					ZcoIM.sendMessage(data, 'down');
					console.log('zco-im-fileDown:下载成功+', new Date());
				} else if (xhr.response && xhr.response.status == 404) {
					console.log('zco-im-fileDown:文件不存在+', new Date());
				} else if (xhr.response && xhr.response.status == 500) {
					console.log('zco-im-fileDown:系统异常+', new Date());
				}
			};
			xhr.send(null);
		},
	},
	mounted() {
		zcoIMEvent.onUpdateUserInfo(data => {
			if (ZcoIM.type === 'web') {
				this.agent = data;
			} else {
				this.client = data;
			}
		});
		zcoIMEvent.onUpdateChatMessage(data => {
			console.log('zco-im: onUpdateChatMessage', data, new Date());
			this.chatMessage.splice(0, this.chatMessage.length);
			data.forEach(item => {
				// 系统开始双录消息不显示
				if ((item.clientId === 'system' || item.from === 'system') && ['start-recording', 'stop-recording'].includes(item.type)) {
					return;
				}
                if (['start-recording', 'stop-recording'].includes(item.type) && item.data.type === 'system') {
					item.type = item.data.type === 'system' ? 'system-' + item.type : item.type;
}
				if (item.type === 'peer-cmd' && item.data.cmd === 'fill-form' && item.data.data && item.data.data.length > 0) {
					item.data.data.formName = item.data.data.map(item => item.formName).join('、');
				}
				this.chatMessage.push(item);
			});
			console.log('zco-im update chatMessage', this.chatMessage, new Date());
		});
		zcoIMEvent.onPreview(data => {
			console.log(data, 'zco-im onPreview', new Date());
			if (data.type === 'pdf') {
				this.previewPdfURL = data.url.replace(/^http(s)?:\/\//, 'https://');
				if (isMobile()) {
					this.previewPdfURL = './static/pdf/web/viewer.html?file=' + this.previewPdfURL;
				}
				this.$emit('preview', { type: 'pdf', url: this.previewPdfURL });
			}
			if (data.type === 'png') {
				this.previewImagesURL = data.url;
				this.$emit('preview', { type: 'img', url: this.previewImagesURL });
			}
			if (data.type === 'richText') {
				this.previewRichText = data.url;
				this.$emit('preview', { type: 'richText', url: this.previewRichText });
			}
			if (data.type === 'video') {
				this.previewVideoURL = data.url;
				this.$emit('preview', { type: 'video', url: this.previewVideoURL });
			}
		});
		zcoIMEvent.emitChatViewMounted();
	}
};
</script>

<style>
.web {
	max-height: calc(100% - 44px - 80px);
}
.chat-message-container {
	width: 100%;
	max-height: calc(100% - 44px - 80px);
	overflow: auto;
	padding: 12px 0;
	box-sizing: border-box;
}
.chat-message-container .agent-box {
	padding: 12px 0;
	display: flex;
	padding-right: 18px;
	flex-flow: row-reverse;
}
.chat-message-container .agent-box .agent-message .agent-name {
	text-align: right;
	padding-bottom: 6px;
	margin: 0;
	font-size: 12px;
	color: #666666;
}
.chat-message-container .agent-box .agent-message .message-box .text .zco-message-container p {
	font-size: 12px;
	font-weight: 400;
	color: #ffffff;
	padding: 8px 12px;
	margin: 0;
	background: #252b48;
	border-radius: 4px;
	max-width: 240px;
	overflow: hidden;
	word-break: break-word;
}
.chat-message-container .client-box {
	padding: 12px 0;
	display: flex;
	padding-left: 14px;
}
.chat-message-container .client-box .client-message .message-box .text .zco-message-container p {
	max-width: 192px;
	overflow: hidden;
	word-break: break-word;
	background: #e8eeff;
	/* box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.08); */
	border-radius: 4px;
	font-size: 12px;
	padding: 8px 12px;
}
.chat-message-container .client-box .client-message .client-name {
	margin: 0;
	font-size: 12px;
	color: #666666;
	margin-bottom: 6px;
}
.message-box {
	display: flex;
}
.zco-business-message {
	font-size: 12px;
	color: #909299;
	display: flex;
	padding: 0 8px;
	align-items: end;
	margin: 0;
}
</style>

<style scoped>
/* 设置滚动条的样式 */
::-webkit-scrollbar {
	width: 6px;
}
/* 滚动槽 */
::-webkit-scrollbar-track {
	-webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.3);
	border-radius: 10px;
}
/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
	border-radius: 10px;
	background: rgba(0, 0, 0, 0.1);
	-webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.5);
}
::-webkit-scrollbar-thumb:window-inactive {
	background: #dddfe1;
}
</style>
